package container;

import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.Friend;
import model.Group;
import utgame.UtMessage.GroupInfo;
import utgame.UtMessage.MS_RequestFriends;
import utgame.UtMessage.MS_CreateGroup;

/**
 * Created by xueal on 2018/1/29.
 */

public class GroupManager {

    private static final GroupManager single = new GroupManager();
    public static GroupManager getInstance() { return single; }

    private Map<String, Group> mGroupMap = new HashMap<>();
    private List<Group> mGroupList = new ArrayList<>();

    public final List<Group> getGroupList() {return mGroupList;}
    public Group getGroup(String name) {return mGroupMap.get(name);}

    public void saveGroups(byte[] message){

        MS_RequestFriends requestFriends = null;
        try {
            requestFriends = MS_RequestFriends.parseFrom(message);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

        if (requestFriends == null) return;

        mGroupMap.clear();
        mGroupList.clear();

        List<GroupInfo> groupInfoList = requestFriends.getGroupList();
        for (int i = 0; i < groupInfoList.size(); ++i){
            GroupInfo groupInfo = groupInfoList.get(i);
            Group group = new Group(Friend.imageIds[i % Friend.imageIds.length],
                    groupInfo.getName(), groupInfo.getMemberNameList());
            mGroupMap.put(groupInfo.getName(), group);
            mGroupList.add(group);
        }
    }

    public void handleCreateGroup(byte[] message){

        MS_CreateGroup msCreateGroup = null;
        try {
            msCreateGroup = MS_CreateGroup.parseFrom(message);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

        if (msCreateGroup == null) return;

        if (msCreateGroup.getErrorCode() != 0) return;

        GroupInfo groupInfo = msCreateGroup.getGroup();
        mGroupMap.put(groupInfo.getName(), new Group(Friend.imageIds[0],
                groupInfo.getName(), groupInfo.getMemberNameList()));
    }

}
